package com.lulin.mall.seckill.schedule;

import com.lulin.mall.seckill.service.SeckillService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 秒杀活动的商品，定时任务上架
 *
 * @author lulin
 * @date 2023/1/4 9:20
 */
@Slf4j
@Component
public class SeckillSkuSchedule {

    @Autowired
    SeckillService seckillService;

    @Autowired
    RedissonClient redissonClient;

    /**
     * 上架未来3天的秒杀活动的商品
     */
    @Async
    @Scheduled(cron = "0 * * * * *") //每分钟执行1次
    public void uploadSeckillSku3Days() {
        log.info("秒杀的商品定时上架任务开始执行了-----" + new Date());
        //分布式锁
        RLock lock = redissonClient.getLock("seckill:upload:lock");
        lock.lock(10, TimeUnit.SECONDS);//加锁

        try {
            //调用上架商品的方法
            seckillService.uploadSeckillSku3Days();
        } catch (Exception e) {
            lock.unlock();//释放锁
        }
        log.info("1次调用结束----");

    }
}
